package org.amos.gateway.filter;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.reactor.model.SaResponseForReactor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.amos.core.basic.vo.R;
import org.amos.gateway.properties.AuthProperties;
import org.amos.gateway.utils.WebFluxUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpResponse;

/**
 * [Sa-Token 权限认证] 拦截器
 *
 */
@Configuration
public class AuthFilter implements Ordered {

    /**
     * 注册 Sa-Token 全局过滤器
     */
    @Bean
    public SaReactorFilter saReactorFilter(AuthProperties properties) {
        return new SaReactorFilter()
                // 拦截与排除 path
                .addInclude("/**")
                .addExclude("/favicon.ico","/actuator/**")
                // 全局认证函数
                .setAuth(obj -> {
                    // 登录校验 -- 拦截所有路由
                    SaRouter.match("/**")
                            .notMatch(properties.getExcludeUrls())
                            .check(r -> {
                                // 检查是否登录 是否有token
                                StpUtil.checkLogin();
                            });
                })
                // 异常处理函数
                .setError(e -> {
                    SaResponseForReactor reactor = (SaResponseForReactor) SaHolder.getResponse();
                    return WebFluxUtils.writeJsonResponse((ServerHttpResponse) reactor.getSource(), R.error(e.getMessage()));
                })
                // 前置函数：在每次认证函数之前执行
                .setBeforeAuth(obj -> {
                    // ---------- 设置跨域响应头 ----------
                    SaHolder.getResponse()
                            // 允许指定域访问跨域资源
                            .setHeader("Access-Control-Allow-Origin", "*")
                            // 允许所有请求方式
                            .setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
                            // 有效时间
                            .setHeader("Access-Control-Max-Age", "3600")
                            // 允许的header参数
                            .setHeader("Access-Control-Allow-Headers", "*");

                    // 如果是预检请求，则立即返回到前端
                    SaRouter.match(SaHttpMethod.OPTIONS)
                            .free(r -> {})
                            .back();
                });

    }

    @Override
    public int getOrder() {
        return FilterOrder.AUTH_FILTER_ORDER;
    }
}
